package com.best.onegous;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.best.onegous.Adapter.JieXiaoAdapter;
import com.best.onegous.Refresh.XListView;
import com.best.onegous.Refresh.XListView.IXListViewListener;
import com.best.onegous.agreement.ApiInterface;
import com.best.onegous.http.BusinessResponse;
import com.best.onegous.http.HttpClients;
import com.loopj.android.http.RequestParams;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Periphery extends Fragment implements IXListViewListener,
		BusinessResponse {
	private XListView mListView;
	private List<JSONObject> mDatas = new ArrayList<JSONObject>();
	private JieXiaoAdapter mAdapter;
	private HttpClients httpclient;
	private int page = 1;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_search, container, false);
		mListView = (XListView) view.findViewById(R.id.listview);
		mAdapter = new JieXiaoAdapter(getActivity(), mDatas);
		mListView.setAdapter(mAdapter);
		mListView.setPullRefreshEnable(true);
		mListView.setPullLoadEnable(true);
		mListView.setXListViewListener(this);
		httpclient = new HttpClients(getActivity());
		httpclient.addResponseListener(this);
		Load();
		return view;
	}
	private void Load() {
		RequestParams params = new RequestParams();
		params.add("p", page + "");
		httpclient.httpclient(ApiInterface.ZUIXINJIEXIAO, params, true);
	}
	@Override
	public void onLoadMore() {
		page++;
		Load();
		/*Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mListView.stopLoadMore();
			}
		}, 2000);*/
	}
	@Override
	public void onRefresh() {
		page = 1;
		Load();
	}
	@Override
	public void OnMessageResponse(String url, JSONObject jo)
			throws JSONException {
		if (url.equals(ApiInterface.ZUIXINJIEXIAO)){
			if(page == 1){
				mListView.stopRefresh();
				mDatas.clear(); 
			}else{
				mListView.stopLoadMore();
			}
			if (null != jo) {
				JSONArray Rows = jo.getJSONArray("Rows");
				for(int i = 0,s = Rows.length();i<s;i++){
					mDatas.add(Rows.getJSONObject(i));
				}
				mAdapter.notifyDataSetChanged();
			}
		}
	}
}
